import logging
import os
import sys
from datetime import datetime
from pathlib import Path
from logging.handlers import RotatingFileHandler

class ColorTriggerLogger:
    """颜色触发器专用日志管理器"""
    
    def __init__(self, log_dir="logs", max_file_size=10*1024*1024, backup_count=5):
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(exist_ok=True)
        
        # 创建不同级别的日志记录器
        self.setup_loggers(max_file_size, backup_count)
        
    def setup_loggers(self, max_file_size, backup_count):
        """设置日志记录器"""
        
        # 主日志记录器
        self.main_logger = logging.getLogger('color_trigger.main')
        self.main_logger.setLevel(logging.DEBUG)
        
        # 性能日志记录器
        self.perf_logger = logging.getLogger('color_trigger.performance')
        self.perf_logger.setLevel(logging.INFO)
        
        # 错误日志记录器
        self.error_logger = logging.getLogger('color_trigger.error')
        self.error_logger.setLevel(logging.ERROR)
        
        # 清除现有处理器
        for logger in [self.main_logger, self.perf_logger, self.error_logger]:
            logger.handlers.clear()
        
        # 创建格式化器
        detailed_formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
        )
        simple_formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(message)s'
        )
        
        # 主日志文件处理器
        main_handler = RotatingFileHandler(
            self.log_dir / 'main.log',
            maxBytes=max_file_size,
            backupCount=backup_count,
            encoding='utf-8'
        )
        main_handler.setFormatter(detailed_formatter)
        self.main_logger.addHandler(main_handler)
        
        # 性能日志文件处理器
        perf_handler = RotatingFileHandler(
            self.log_dir / 'performance.log',
            maxBytes=max_file_size,
            backupCount=backup_count,
            encoding='utf-8'
        )
        perf_handler.setFormatter(simple_formatter)
        self.perf_logger.addHandler(perf_handler)
        
        # 错误日志文件处理器
        error_handler = RotatingFileHandler(
            self.log_dir / 'error.log',
            maxBytes=max_file_size,
            backupCount=backup_count,
            encoding='utf-8'
        )
        error_handler.setFormatter(detailed_formatter)
        self.error_logger.addHandler(error_handler)
        
        # 控制台处理器（仅显示重要信息）
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(simple_formatter)
        
        # 只为主日志记录器添加控制台输出
        self.main_logger.addHandler(console_handler)
        
    def debug(self, message, *args, **kwargs):
        """调试日志"""
        self.main_logger.debug(message, *args, **kwargs)
        
    def info(self, message, *args, **kwargs):
        """信息日志"""
        self.main_logger.info(message, *args, **kwargs)
        
    def warning(self, message, *args, **kwargs):
        """警告日志"""
        self.main_logger.warning(message, *args, **kwargs)
        
    def error(self, message, *args, **kwargs):
        """错误日志"""
        self.main_logger.error(message, *args, **kwargs)
        self.error_logger.error(message, *args, **kwargs)
        
    def critical(self, message, *args, **kwargs):
        """严重错误日志"""
        self.main_logger.critical(message, *args, **kwargs)
        self.error_logger.critical(message, *args, **kwargs)
        
    def performance(self, message, *args, **kwargs):
        """性能日志"""
        self.perf_logger.info(message, *args, **kwargs)
        
    def log_detection_performance(self, detection_time, trigger_count, color_matches):
        """记录检测性能"""
        self.performance(
            f"检测性能 - 耗时: {detection_time:.3f}s, 触发器: {trigger_count}, 匹配: {color_matches}"
        )
        
    def log_system_performance(self, cpu_usage, memory_usage, thread_count):
        """记录系统性能"""
        self.performance(
            f"系统性能 - CPU: {cpu_usage:.1f}%, 内存: {memory_usage:.1f}MB, 线程: {thread_count}"
        )
        
    def log_error_with_context(self, error, context=None):
        """记录带上下文的错误"""
        error_msg = f"错误: {error}"
        if context:
            error_msg += f" | 上下文: {context}"
        self.error(error_msg)
        
    def log_hotkey_event(self, event_type, key, success=True):
        """记录热键事件"""
        status = "成功" if success else "失败"
        self.info(f"热键事件 - {event_type}: {key} - {status}")
        
    def log_color_detection(self, trigger_name, color_detected, target_color, current_color):
        """记录颜色检测事件"""
        status = "匹配" if color_detected else "不匹配"
        self.debug(
            f"颜色检测 - {trigger_name}: {status} | 目标: {target_color} | 当前: {current_color}"
        )
        
    def log_config_operation(self, operation, filename, success=True):
        """记录配置操作"""
        status = "成功" if success else "失败"
        self.info(f"配置操作 - {operation}: {filename} - {status}")
        
    def get_log_stats(self):
        """获取日志统计信息"""
        stats = {}
        
        for log_file in ['main.log', 'performance.log', 'error.log']:
            file_path = self.log_dir / log_file
            if file_path.exists():
                stat = file_path.stat()
                stats[log_file] = {
                    'size': stat.st_size,
                    'modified': datetime.fromtimestamp(stat.st_mtime),
                    'lines': self._count_lines(file_path)
                }
            else:
                stats[log_file] = {'size': 0, 'modified': None, 'lines': 0}
                
        return stats
        
    def _count_lines(self, file_path):
        """计算文件行数"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return sum(1 for _ in f)
        except Exception:
            return 0
            
    def clear_logs(self):
        """清除所有日志文件"""
        try:
            for log_file in self.log_dir.glob('*.log*'):
                log_file.unlink()
            self.info("日志文件已清除")
            return True
        except Exception as e:
            self.error(f"清除日志文件失败: {e}")
            return False
            
    def export_logs(self, export_path):
        """导出日志文件"""
        try:
            import shutil
            export_dir = Path(export_path)
            export_dir.mkdir(exist_ok=True)
            
            for log_file in self.log_dir.glob('*.log'):
                shutil.copy2(log_file, export_dir)
                
            self.info(f"日志文件已导出到: {export_dir}")
            return True
        except Exception as e:
            self.error(f"导出日志文件失败: {e}")
            return False

# 全局日志实例
logger = ColorTriggerLogger()

# 便捷函数
def debug(message, *args, **kwargs):
    logger.debug(message, *args, **kwargs)

def info(message, *args, **kwargs):
    logger.info(message, *args, **kwargs)

def warning(message, *args, **kwargs):
    logger.warning(message, *args, **kwargs)

def error(message, *args, **kwargs):
    logger.error(message, *args, **kwargs)

def critical(message, *args, **kwargs):
    logger.critical(message, *args, **kwargs)

def performance(message, *args, **kwargs):
    logger.performance(message, *args, **kwargs)
